<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Validate;
use app\util\Utils;
use think\Db;
use app\admin\model\Code;
use app\api\model\Item;
use app\api\model\ItemImg;
use app\api\model\ItemProcess;
use app\api\model\Store;
use app\api\model\StoreRoom;
use app\api\model\StoreRoomBed;
use app\api\model\StoreImg;
use app\api\model\Yuyue;
use app\api\model\CtmCollect;
use app\api\model\Comment;
use app\api\model\NewPeopleToItem;
use app\api\model\Miaosha;
use app\api\model\StaffBindStore;
use app\api\model\Staff;
use app\api\model\ItemClass;
use app\api\model\Custom;
use app\api\model\CtmCun;
use app\api\model\Coupon;
use app\util\File;
use think\Cache;

class WitdeskController extends Controller {
    /*
     * 这是智慧前台的接口 公司内部用的
     * 调用方法为 前端调用
     */

    /*
     * code列表
     */

    public function code() {
        /*
         * 0  成功
         * 1  参数错误
         * 2  验证失败
         * 3  请求黑名单
         * 4  token无效
         * 3001  没有发现此项目
         * 3002  此项目已经下架
         * 3003  没有发现此秒杀
         * 3004  此秒杀已下架
         * 3005
         * 3006
         */
    }

    /*
     * 返回数据
     */

    public static function ajaxReturn($code, $msg, $data) {
        $return = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ];

        return $return;
    }
    
    /*
     * 门店介绍
     * 作者 xfwed
     * 日期 2020-11-16
     *
     * @param number robot_no 机器mac码
     */

    public function storeInfo() {
        $rule = [
            'robot_no' => 'require',
        ];
        $msg = [
            'robot_no.require' => '机器编码必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $robot_no = $all['robot_no'];  
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->where('is_delete',0)
                ->value('store_id');
        //操作流程图
        $storeInfo['handleChart']= 'http://47.104.83.107/images/kkmimg/kkmaiqt/handleChart.png';
        $storeRow = Store::where('id',$storeId)
                ->field('id,store_name,store_scale,busstarttime,busendtime,xcxcode')
                ->find();
        $storeInfo['storeInfo'] = $storeRow;
        $storeRoomNum = StoreRoom::where('store_id',$storeId)
                ->where('active',1)
                ->where('is_delete',1)
                ->count();
        $storeInfo['storeRoomNum'] = $storeRoomNum;
        $storeRoomIds = StoreRoom::where('store_id',$storeId)
                ->where('active',1)
                ->where('is_delete',1)
                ->column('id');
        $storeRoomBedNum = StoreRoomBed::where('room_id','in',$storeRoomIds)
                ->where('active',1)
                ->where('is_delete',1)
                ->count();
        $storeInfo['storeRoomBedNum'] = $storeRoomBedNum;
        //店内环境
        $storeImg = StoreImg::where('store_id',$storeId)
                ->field('img')
                ->select();
        if(count($storeImg)<3){
           $storeImg = [
               ['img'=>'http://47.104.83.107/images/kkmimg/kkmaiqt/store1.png'],
               ['img'=>'http://47.104.83.107/images/kkmimg/kkmaiqt/store2.png'],
               ['img'=>'http://47.104.83.107/images/kkmimg/kkmaiqt/store3.png'],
               ]; 
        }
        $storeInfo['storeImg'] = $storeImg;
        //多功能间
        $storeFlexoRoomNum = StoreRoom::where('store_id',$storeId)
                ->where('active',1)
                ->where('is_delete',1)
                ->where('smart_status',1)
                ->count();
        $storeFlexoRoomList = StoreRoom::where('store_id',$storeId)
                ->where('active',1)
                ->where('is_delete',1)
                ->where('smart_status',1)
                ->field('id,room_name,room_image')
                ->select();
        foreach ($storeFlexoRoomList as $k => $v){
            $storeFlexoRoomList[$k]['bedNum'] = StoreRoomBed::where('room_id',$v['id'])
                    ->where('active',1)
                    ->where('is_delete',1)
                    ->count();
        }
        $storeInfo['storeFlexoRoomNum'] = $storeFlexoRoomNum;
        $storeInfo['storeFlexoRoomList'] = $storeFlexoRoomList;
        //智能间
        $storeWitRoomNum = StoreRoom::where('store_id',$storeId)
                ->where('active',1)
                ->where('is_delete',1)
                ->where('smart_status',2)
                ->count();
        $storeWitRoomList = StoreRoom::where('store_id',$storeId)
                ->where('active',1)
                ->where('is_delete',1)
                ->where('smart_status',2)
                ->field('id,room_name,room_image')
                ->select();
        foreach ($storeWitRoomList as $k => $v){
            $storeWitRoomList[$k]['bedNum'] = StoreRoomBed::where('room_id',$v['id'])
                    ->where('active',1)
                    ->where('is_delete',1)
                    ->count();
        }
        $storeInfo['storeWitRoomNum'] = $storeWitRoomNum;
        $storeInfo['storeWitRoomList'] = $storeWitRoomList;
        return $this->ajaxReturn(0, '查询成功',$storeInfo);
    }
    
    /*
     * 周边门店
     * 作者 xfwed
     * 日期 2020-11-16
     *
     * @param number storeId 店铺id
     */

    public function nearbyStoreList() {
        $rule = [
            'robot_no' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'robot_no.require' => '店铺id必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $robot_no = $all['robot_no'];  
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->where('is_delete',0)
                ->value('store_id');
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        
        $storeRow = Store::where('id',$storeId)
                ->field('id,store_name,longitude,latitude,city')
                ->find();
        $longitude = $storeRow['longitude'];
        $latitude = $storeRow['latitude'];
        $city = $storeRow['city'];
        $storeList = Store::where('auditstore',1)
                ->where('is_del',1)
                ->where('city',$city)
                ->where('id','<>',$storeId)
                ->field('id,store_name,longitude,latitude')
                ->field("id, store_name, store_address,logoimg, add_time, round(st_distance(point(longitude, latitude), point({$longitude}, {$latitude})) * 111195) as distance")
                ->order('distance asc')
                ->limit($offset, $perPage)
                ->select();
        foreach ($storeList as $k => $v){
            //店铺星级
            $commentStarNum = Comment::where('store_id',$v['id'])->sum('store_star');
            $commentNum = Comment::where('store_id',$v['id'])->count();
            
            if($commentNum != 0){
                $storeStar = round($commentStarNum/$commentNum,1);
            }  else {
                $storeStar = 5;
            }
            
            $storeList[$k]['storeStar'] = $storeStar;
            //服务人次
            $serNum = Yuyue::where('store_id',$v['id'])
                    ->where('status','in','4,7,8')
                    ->count();
            $storeList[$k]['serNum'] = $serNum;
            //喜欢人数
            $collectNum = CtmCollect::where('type',3)
                    ->where('pro_id',$v['id'])
                    ->count();
            $storeList[$k]['collectNum'] = $collectNum;
        }
        return $this->ajaxReturn(0, '查询成功',$storeList);
    }
    
    /*
     * 项目列表
     * 作者 xfwed
     * 日期 2020-11-16
     *
     * @param number storeId 店铺id
     */

    public function itemList() {
        $rule = [
            'robot_no' => 'require',
            'type' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'robot_no.require' => '店铺id为数字',
            'type.integer' => '类型必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $robot_no = $all['robot_no'];  
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->where('is_delete',0)
                ->value('store_id');
        $type = $all['type'];//项目分类
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        //查询图标
        $iconList = ItemClass::where('type',0)
                ->where('id','in','3,4,5,7,10,12,11,13,15,9,14')
                ->field('id,name,icon')
                ->orderRaw("id=3 desc,id=4 desc,id=5 desc,id=7 desc,id=10 desc,id=12 desc,id=11 desc,id=13 desc,id=15 desc,id=9 desc,id=14 desc")
                ->select();
        $iconList[11]['id'] = 0;
        $iconList[11]['name'] = '全部';
        $iconList[11]['icon'] = 'http://47.104.83.107/images/kkmimg/kkmai/admin/20201130/all.png';
        $data['iconList'] = $iconList;
        
        if($type){
            $where['item_type'] = $type;
        }

        $where['is_del'] = 1;
        $where['status'] = 2;
        $list = Item::where($where)
                ->field('id item_id,item_name,item_price,special_money,item_img,sell_count,xcx_img')
                ->order('sell_count desc')
                ->limit($offset, $perPage)
                ->select();
        
        foreach ($list as $k => $v){
            $list[$k]['collectNum'] = CtmCollect::where('pro_id',$v['item_id'])
                    ->where('type',1)
                    ->count();
            $commentRow = Comment::alias('p')
                    ->join('custom c','c.id = p.ctm_id','left')
                    ->where('p.item_id',$v['item_id'])
                    ->where('p.item_star',5)
                    ->where('p.item_content','<>','')
                    ->field('p.item_content,c.custom_photo')
                    ->find();
            $list[$k]['commentImg'] = $commentRow['custom_photo'];
            $list[$k]['commentContent'] = $commentRow['item_content'];
            
            $key = $v['item_id'].'_'.$storeId;
            $name = Cache::get($key);
            if ($name) {
                 $xcx_img = $name;
            } else {
                //生成项目二维码
                $ApiPath = config('appconfig.ApiPath');
                $postFields['param'] = 'a='.$v['item_id'].'&s='.$storeId;
                $postFields['url'] = 'packageA/pages/project/projectDetail/index';
                $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
                $IndexPath = config('appconfig.IndexPath');
                $relust = json_decode($relust, true)['data'];
                $arr = explode(",", $relust);
                $last = $arr[1];
                $postFields1['img'] = $last;
                $postFields1['modeName'] = 'itemqrcode';
                $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
                $relust = json_decode($relust, true)['data'];

                Cache::set($key, $relust);
                $xcx_img = $relust;
            }
            $list[$k]['xcx_img'] = $xcx_img;
        }
        $data['itemList'] = $list;
        
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    
    /*
     * 项目详情
     * 作者 xfwed
     * 日期 2020-11-17
     *
     * @param number itemId 项目id
     */

    public function itemInfo() {
        $rule = [
            'itemId' => 'require',
            'robot_no' => 'require',
        ];
        $msg = [
            'itemId.require' => '项目ID必须',
            'robot_no.require' => '机器编码必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }

        $itemId = $all['itemId'];  
        $robot_no = $all['robot_no'];  
        
        $row = Item::where('id',$itemId)->find();
        if(empty($row)){
            return $this->ajaxReturn(3001, '没有发现此项目', null);  
        }
        if($row['is_del'] == 2){
            return $this->ajaxReturn(3002, '此项目已经下架', null);  
        }
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',4)
                ->where('robot_no',$robot_no)
                ->value('store_id');
        //查询项目购买二维码是否存在  不存在生成
        if(empty($row['xcx_img'])){
            $ApiPath = config('appconfig.ApiPath');
            $postFields['param'] = 'a='.$itemId.'&s='.$storeId;
            $postFields['url'] = 'packageA/pages/project/projectDetail/index';
            $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
            $IndexPath = config('appconfig.IndexPath');
            $relust = json_decode($relust, true)['data'];
            $arr = explode(",", $relust);
            $last = $arr[1];
            $postFields1['img'] = $last;
            $postFields1['modeName'] = 'itemqrcode';
            $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
            $relust = json_decode($relust, true)['data'];
            Item::where('id',$itemId)->update(['xcx_img'=>$relust]);
        }
        $itemRow = Item::where('id',$itemId)
                ->field('id,item_name,vice_name,item_price,special_money,item_img,people,service_time,content,xcx_img,sell_count')
                ->find();
        //查询项目图片
        $itemimg = ItemImg::where('item_id',$itemId)->field('img')->select();
        $itemRow['itemimg'] = $itemimg;
        //查询项目评价
        $commentList = Comment::alias('t')
                ->join('custom c','c.id = t.ctm_id','left')
                ->join('staff s','s.id = t.staff_id','left')
                ->where('t.item_id',$itemId)
                ->order('add_time desc')
                ->field('t.item_star,t.item_content,t.item_image,t.reply_content,t.add_time,c.custom_photo,c.custom_name,s.staff_name')
                ->select();
        $itemRow['commentList'] = $commentList;
        return $this->ajaxReturn(0, '查询成功',$itemRow);
    }
    
    /*
     * 秒杀详情
     * 作者 xfwed
     * 日期 2020-11-18
     *
     * @param number itemId 项目id
     */

    public function miaoshaInfo() {
        $rule = [
            'id' => 'require',
            'robot_no' => 'require',
        ];
        $msg = [
            'id.require' => '秒杀ID必须',
            'robot_no.require' => '机器编码必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }

        $id = $all['id'];  
        $robot_no = $all['robot_no'];  
        $miaoshaRow = Miaosha::where('id',$id)->find();
        if(empty($miaoshaRow)){
            return $this->ajaxReturn(3003, '没有发现此秒杀', null);
        }
        if(empty($miaoshaRow['is_del']==2)){
            return $this->ajaxReturn(3004, '此秒杀已下架', null);
        }
        $itemId = $miaoshaRow['item_id'];
        $row = Item::where('id',$itemId)->find();
        
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->value('store_id');
        //查询项目购买二维码是否存在  不存在生成
        if(empty($miaoshaRow['xcx_img'])){
            $ApiPath = config('appconfig.ApiPath');
            $postFields['param'] = 'id='.$miaoshaRow['id'].'&s='.$storeId.'&m_id=0';
            $postFields['url'] = 'packageA/pages/seckillDesc/seckillDesc';
            $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
            $IndexPath = config('appconfig.IndexPath');
            $relust = json_decode($relust, true)['data'];
            $arr = explode(",", $relust);
            $last = $arr[1];
            $postFields1['img'] = $last;
            $postFields1['modeName'] = 'itemqrcode';
            $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
            $relust = json_decode($relust, true)['data'];
            Miaosha::where('id',$miaoshaRow['id'])->update(['xcx_img'=>$relust]);
        }
        //查询秒杀详细
        $miaoshaRow = Miaosha::where('id',$id)
                ->field('id,name,price,item_price,number,sell_count,xcx_img')
                ->find();
        
        $itemRow = Item::where('id',$itemId)
                ->field('id,item_name,vice_name,item_img,people,service_time,content')
                ->find();
        //查询项目图片
        $itemimg = ItemImg::where('item_id',$itemId)->field('img')->select();
        $itemRow['itemimg'] = $itemimg;
        //查询项目评价
        $commentList = Comment::alias('t')
                ->join('custom c','c.id = t.ctm_id','left')
                ->join('staff s','s.id = t.staff_id','left')
                ->where('t.item_id',$itemId)
                ->order('add_time desc')
                ->field('t.item_star,t.item_content,t.item_image,t.reply_content,t.add_time,c.custom_photo,c.custom_name,s.staff_name')
                ->select();
        $itemRow['commentList'] = $commentList;
        $data['miaoshaInfo'] = $miaoshaRow;
        $data['itemInfo'] = $itemRow;
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    
    /*
     * 美容师列表
     * 作者 xfwed
     * 日期 2020-11-18
     *
     * @param number storeId 店铺id
     */

    public function staffList() {
        $rule = [
            'robot_no' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'robot_no.require' => '机器编码必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $robot_no = $all['robot_no']; 
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->value('store_id');
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        //查询店铺的营业时间
        $storeRow = Store::where('id',$storeId)->field('busstarttime,busendtime')->find();
        $data['storeInfo'] = $storeRow;
        
        $stassList = StaffBindStore::alias('b')
                ->join('staff s','s.id = b.staff_id','left')
                ->where('b.store_id',$storeId)
                ->where('s.staff_on',1)
                ->where('s.status',1)
                ->where('s.is_job',1)
                ->field('s.id,s.staff_name,s.nickname,s.staff_rank,s.staff_year,s.staff_photo,s.mini_code')
                ->order('s.id asc')
//                ->limit($offset, $perPage)
                ->select();
        foreach ($stassList as $k => $v){
            $key = 'staff_id'.$v['id'];
            $name = Cache::get($key);
            if ($name) {
                 $mini_code = $name;
            } else {
                //生成项目二维码
                $ApiPath = config('appconfig.ApiPath');
                $postFields['param'] = 'sid='.$v['id'];
                $postFields['url'] = 'pages/index/staffDesc/staffDesc';
                $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
                $IndexPath = config('appconfig.IndexPath');
                $relust = json_decode($relust, true)['data'];
                $arr = explode(",", $relust);
                $last = $arr[1];
                $postFields1['img'] = $last;
                $postFields1['modeName'] = 'staffqrcode';
                $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
                $relust = json_decode($relust, true)['data'];

                Cache::set($key, $relust);
                $mini_code = $relust;
            }
            $stassList[$k]['mini_code'] = $mini_code;
            
            $stassList[$k]['rankname'] = Db::name('staff_rank')->where('id',$v['staff_rank'])->value('name');
            //服务人次
            $stassList[$k]['serNum'] = Yuyue::where('staff_id',$v['id'])
                    ->where('status','in','4,7,8')
                    ->count();
            //满意度
            $staffStar = Comment::where('staff_id',$v['id'])->avg('staff_star');
            if(empty($staffStar)){
                $staffStar = 5;
            }
            $stassList[$k]['starPer'] = bcdiv($staffStar,5,2);  
            //是否打卡
            $start_time=strtotime(date("Y-m-d",time()));
            $end_time=$start_time+60*60*24;
            $start_time=date("Y-m-d H:i:s",$start_time);       
            $end_time=date("Y-m-d H:i:s",$end_time); 
            $sign = Db::name('staff_sign')->where('staff_id',$v['id'])
                    //->where('store_id',$storeId)
                    ->where('add_time','between',[$start_time,$end_time])
                    ->where('status',1)
                    ->find();
            if($sign){
                $stassList[$k]['sign'] = 1;
            }  else {
                $stassList[$k]['sign'] = 2;
            }
            //美容师状态
            $now = date('Y-m-d H:i:s');
            $now2 = date('Y-m-d H:i:s',time()+2700);
            $yuyueRow = Yuyue::where('staff_id',$v['id'])
                    ->where('status','in','2,3,13')
                    ->where('start_time','between',[$now,$now2])
                    ->find();
            if($yuyueRow){
                $staffStatus = 1;//正在忙碌 2可以预约
            }  else {
                $staffStatus = 2;//正在忙碌 2可以预约
            }
            $stassList[$k]['staffStatus'] = $staffStatus;
            //多久可以为你服务
            if($sign){//打卡了
                $yuyueList = Yuyue::where('staff_id',$v['id'])
                    ->where('status','in','2,3,13')
                    ->where('start_time','between',[$now,$now2])
                    ->select();
                $yuyueList2 = Yuyue::where('staff_id',$v['id'])
                    ->where('status','in','2,3,13')
                    ->where('start_time','>',$now)
                    ->order('start_time asc')
                    ->select();
                if(empty($yuyueList)){
                    $timeStatus = 0;
                    $order = 0;
                }  else {
                    $timeArr = [];
                    foreach ($yuyueList2 as $key=>$val){
                        $service_time = Item::where('id',$val['item_id'])->value('service_time');
                        $end = strtotime($val['start_time'])+$service_time*60;
                        $end = date('Y-m-d H:i:s',$end);
                        $timeArr[$key] = ['start'=>$val['start_time'],'end'=>$end];
                    }
                    for($i=0;$i<count($timeArr);$i++){
                        if($i+1>=count($timeArr)){//最后一个
                            $timeStatus = strtotime($timeArr[$i]['end'])-time();
                            $order = $timeStatus;
                            break;
                        }  else {
                            $cha = strtotime($timeArr[$i+1]['start'])-strtotime($timeArr[$i]['end']);
                            if($cha >= 1800){//大于半小时
                                $timeStatus = strtotime($timeArr[$i]['end'])-time();
                                $order = $timeStatus;
                                break;
                            }
                        }
                    }
                }
            }  else {
                $timeStatus = -1;
                $order = 9999999999999999999;
            }
            $stassList[$k]['timeStatus'] = $timeStatus;
            $stassList[$k]['sort'] = $order;
            //绑定的店铺
            $store_id = Db::name('staff_bind_store')
                    ->where('staff_id',$v['id'])
                    ->column('store_id');
            $storeName = Db::name('store')
                    ->where('id','in',$store_id)
                    ->column('store_name');
           $storeName = implode(',', $storeName);
           $stassList[$k]['storeName'] = $storeName;
        }
        //根据 timeStatus 重新排序
        $timeStatus = array_column($stassList,'sort');
        array_multisort($timeStatus,SORT_ASC,$stassList);
        
        $data['staffList'] = $stassList;
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    
    /*
     * 美容师详情
     * 作者 xfwed
     * 日期 2020-11-18
     *
     * @param number storeId 店铺id
     */

    public function staffInfo() {
        $rule = [
            'id' => 'integer',
        ];
        $msg = [
            'id.integer' => '美容师id为数字',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $id = $all['id'];  
        
        $staffRow = Staff::where('id',$id)
                ->field('id,staff_name,nickname,staff_rank,staff_year,staff_photo,sttaf_intro,mini_code')
                ->find();
        $staffRow['rankname'] = Db::name('staff_rank')->where('id',$staffRow['staff_rank'])->value('name');
        //关注人数
        $staffRow['collectNum'] = CtmCollect::where('pro_id',$id)
                    ->where('type',2)
                    ->count();
        //特长
        $staffRow['hobby'] = Db::name('staff_hobby')->alias('h')
                ->join('item_class c','c.id = h.orther_id','left')
                ->where('h.type',1)
                ->where('h.staff_id',$staffRow['id'])
                ->field('name')
                ->select();
        //相册
        $staffRow['img'] = Db::name('staff_photo')
                ->where('staff_id',$staffRow['id'])
                ->field('photo')
                ->select();
        //服务人次
        $staffRow['serNum'] = Yuyue::where('staff_id',$staffRow['id'])
                ->where('status','in','4,7,8')
                ->count();
        //满意度
        $staffStar = Comment::where('staff_id',$staffRow['id'])->avg('staff_star');
        if(empty($staffStar)){
            $staffStar = 5;
        }
        $staffRow['star'] = $staffStar;  
        $staffRow['starPer'] = bcdiv($staffStar,5,2);  
        
        //查询美容师评价
        $commentList = Comment::alias('t')
                ->join('custom c','c.id = t.ctm_id','left')
                ->join('staff s','s.id = t.staff_id','left')
                ->where('t.staff_id',$staffRow['id'])
                ->order('add_time desc')
                ->field('t.staff_star,t.staff_content,t.staff_image,t.staff_label,t.reply_content,t.add_time,c.custom_photo,c.custom_name,s.staff_name')
                ->select();
        $staffRow['commentList'] = $commentList;
        //评价标签
        $labelList = Db::name('comment_label')
                ->where('type',1)
                ->field('id,name')
                ->select();
        foreach ($labelList as $k => $v){
            $where[] = ['exp', "instr(CONCAT( ',', staff_label, ',' ),  ',".$v['id'].",' )" ];
            $labelList[$k]['num'] = Comment::where('staff_id',$staffRow['id'])
                    ->where('find_in_set('.$v['id'].',staff_label)')
                    ->count();
        }
        
        $num = count($labelList);
        $labelList[$num]['id'] = $num+1;
        $labelList[$num]['name'] = '五星好评';
        $labelList[$num]['num'] = Comment::where('staff_id',$staffRow['id'])->where('staff_star',5)->count();
        
        $labelList[$num+1]['id'] = $num+2;
        $labelList[$num+1]['name'] = '全部';
        $labelList[$num+1]['num'] = $num;
        $last_names = array_column($labelList,'id');
        array_multisort($last_names,SORT_DESC,$labelList);
        $staffRow['labelList'] = $labelList;
        
        return $this->ajaxReturn(0, '查询成功',$staffRow);
    }
    
    /*
     * 我的项目
     * 作者 xfwed
     * 日期 2020-11-30
     *
     * @param number ctmId 用户id
     */

    public function myItem() {
        $rule = [
            'ctmId' => 'require',
            'robot_no' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctmId.require' => '用户id必须',
            'robot_no.require' => '机器编码必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $ctmId = $all['ctmId'];  
        $robot_no = $all['robot_no']; 
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->value('store_id');
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        //多媒体介绍视频路径
        //$data['videoUrl']= 'https://haokan.baidu.com/v?pd=wisenatural&vid=14789299594953327166';
        $start_time=strtotime(date("Y-m-d",time()));
        $end_time=$start_time+60*60*24;
        $start_time=date("Y-m-d H:i:s",$start_time);       
        $end_time=date("Y-m-d H:i:s",$end_time); 
        $list = Yuyue::alias('y')
                ->join('staff s','s.id = y.staff_id','left')
                ->join('item i','i.id = y.item_id','left')
                ->where('y.status','in','3')
                ->where('y.ctm_id',$ctmId)
                ->where('y.store_id',$storeId)
                ->where('y.start_time','between',[$start_time,$end_time])
//                ->where('y.bed_id is null or y.bed_id = 0')
                ->field('y.id,y.start_time,y.room_id,y.bed_id,y.status,y.if_serviceing,i.id item_id,i.item_name,i.item_img,i.service_time,s.staff_name,s.nickname')
                ->order('y.start_time asc')
//                ->limit($offset, $perPage)
                ->select();
        $item_ids = [];
        foreach ($list as $k => $v){
            $row = Db::name('time_occupy_record')->where('type',1)
                    ->where('other_id',$v['id'])
                    ->where('is_del',0)
                    ->field('room_id,bed_id')
                    ->find();
            $roomId = $row['room_id'];
            $bedId = $row['bed_id'];
            
            if($roomId){
                $list[$k]['roomName'] = Db::name('store_room')->where('id',$roomId)->value('room_name');
            }  else {
                $list[$k]['roomName'] = '';
            }
            if($bedId){
                $list[$k]['bedName'] = Db::name('store_room_bed')->where('id',$bedId)->value('bed_name');
            }  else {
                $list[$k]['bedName'] = '';
            }
            //判断状态
            if($v['status'] == 3){
                if($v['room_id']){
                    $list[$k]['serstatus'] = 2;//1未选择2待服务3服务中
                }  else {
                    $list[$k]['serstatus'] = 1;
                }
            }elseif($v['if_serviceing'] == 1) {
                $list[$k]['serstatus'] = 3;
            }
            $item_ids[$k]=$v['item_id'];
            $list[$k]['room_id'] = $roomId;
            $list[$k]['bed_id'] = $bedId;
        }
        $data['list'] = $list;
        //查询今天第几位顾客
        $start_time=strtotime(date("Y-m-d",time()));
        $end_time=$start_time+60*60*24;
        $start_time=date("Y-m-d H:i:s",$start_time);       
        $end_time=date("Y-m-d H:i:s",$end_time);    
        $todayCtmlist = Yuyue::alias('y')
                ->join('custom c','c.id = y.ctm_id','left')
                ->where('y.staff_time','between',[$start_time,$end_time])
                ->where('y.store_id',$storeId)
                ->group('ctm_id')
                //->limit('0,5')
                ->column('custom_photo');
        $data['todayCtmNum'] = count($todayCtmlist)+1;
        $data['todayCtmPhoto'] = $todayCtmlist;
        //查询最优组合的项目
        $bestgroup_itemids = Item::where('id','in',$item_ids)->column('bestgroup_itemids');
        $bestgroup_itemids = implode(",", $bestgroup_itemids);
        $bestgroupList = Item::where('id','in',$bestgroup_itemids)
                ->where('is_del',1)
                ->where('status',2)
                ->field('id,item_type,item_name,item_img,service_time,item_price,special_money,xcx_img')
                ->select();
        //特权会员：立省金额 = 最高额优惠券 + 美容金  若立省金额 > 99，则显示99元
        //非特权会员：立省金额 = 项目原价 - 99 + 最高额优惠券 + 美容金  若立省金额 > 项目原价，则显示项目原价
        $ctmRow = Custom::where('id',$ctmId)->field('vip_status,red_money')->find();
        //查询用户最高代金券金额
        $cunMoney = CtmCun::alias('cc')
                ->join('coupon c','c.id = cc.cun_id')
                ->where('cc.ctm_id',$ctmId)
                ->where('cc.employ',2)
                ->where('cc.end_time','>',date('Y-m-d H:i:s'))
                ->order('c.money desc')
                ->value('c.money');
        if($ctmRow['vip_status'] == 2){
            if($cunMoney){
                if($ctmRow['red_money']>0){
                    $sheng = round(($cunMoney+$ctmRow['red_money'])/100,2);
                    if($sheng > 99){
                        $sheng = 99;
                    }
                    $note = '此项目可使用优惠券和美容金，最多为您立省'.$sheng.'元';
                }  else {
                    $sheng = round($cunMoney/100,2);
                    if($sheng > 99){
                        $sheng = 99;
                    }
                    $note = '此项目可使用优惠券，最多为您立省'.$sheng.'元';
                }
            }  else {
                if($ctmRow['red_money']>0){
                    $sheng = round($ctmRow['red_money']/100,2);
                    if($sheng > 99){
                        $sheng = 99;
                    }
                    $note = '此项目可使用美容金，最多为您立省'.$sheng.'元';
                }  else {
                    $note = '';
                }
            }
        }
        foreach ($bestgroupList as $k => $v){
            if($ctmRow['vip_status'] == 2){
                $bestgroupList[$k]['note'] = $note;
            }  else {
                $sheng = round(($v['item_price']-9900+$cunMoney+$ctmRow['red_money'])/100,2);
                $note = '开通99特权会员可立省'.$sheng.'元';
                $bestgroupList[$k]['note'] = $note;
            }
            //查询项目分类名
            $item_type = $v['item_type'];
            $bestgroupList[$k]['className'] = ItemClass::where('id',$item_type)->value('name');
            
            //生成项目二维码
            $key = $v['id'].'_'.$storeId;
            $name = Cache::get($key);
            if ($name) {
                 $xcx_img = $name;
            } else {
                //生成项目二维码
                $ApiPath = config('appconfig.ApiPath');
                $postFields['param'] = 'a='.$v['id'].'&s='.$storeId;
                $postFields['url'] = 'packageA/pages/project/projectDetail/index';
                $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/',json_encode($postFields));
                $IndexPath = config('appconfig.IndexPath');
                $relust = json_decode($relust, true)['data'];
                $arr = explode(",", $relust);
                $last = $arr[1];
                $postFields1['img'] = $last;
                $postFields1['modeName'] = 'itemqrcode';
                $relust = Utils::curlPost1($IndexPath.'Public/uploadBase64Img/',$postFields1);
                $relust = json_decode($relust, true)['data'];

                Cache::set($key, $relust);
                $xcx_img = $relust;
            }
            $bestgroupList[$k]['xcx_img'] = $xcx_img;
        }
        $data['bestgroupList'] = $bestgroupList;
        
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    
    /*
     * 智慧前台首页广告轮播
     * 作者 xfwed
     * 日期 2020-12-02
     *
     * @param number ctmId 用户id
     */

    public function imgList() {
        $rule = [
            'robot_no' => 'require',
        ];
        $msg = [
            'robot_no.require' => '机器编码必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $robot_no = $all['robot_no']; 
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->value('store_id');
        //查询店铺营业时间
        $storeRow = Store::where('id',$storeId)->field('is_open,decorate_end')->find();
        $data['is_open'] = $storeRow['is_open'];
        $decorate_end = explode(" ",$storeRow['decorate_end']);
        $data['decorate_end'] = $decorate_end[0];
        $data['store_id'] = $storeId;
        //智慧前台广告轮播
        $list = Db::name('pic')->where('type',8)
                ->where('pro_type',3)
                ->where('isshow',1)
                ->field('id,pic,url')
                ->order('sort asc')
                ->select();
//        if($storeId == 42 || $storeId == 86 || $storeId ==46){
//            $n = count($list);
//            $list[$n]['id'] = 10000;
//            $list[$n]['pic'] = 'http://47.104.83.107/images/kkmimg/kkmai/default/hhht.jpg';
//            $list[$n]['url'] = '6666';
//        }
        $data['list'] = $list;
        
        //智慧前台首页轮播	
        $list16 = Db::name('pic')->where('type',16)
                ->where('pro_type',3)
                ->where('isshow',1)
                ->field('id,pic,url')
                ->order('sort asc')
                ->select();
        $data['indexImgs'] = $list16;
        
        $leftQrcode = Store::where('id',$storeId)->value('xcxcode');
        $imageInfo = getimagesize($leftQrcode);
        $base64 = "" . chunk_split(base64_encode(file_get_contents($leftQrcode)));
        $base64_image = chunk_split(base64_encode(file_get_contents($leftQrcode)));
        
        $scene = 'n='.$robot_no;
        $page = 'pages/index/index';
        $file = new File();
        $rightQrcode = $file->generateXcxPagecode($scene,$page);

        $data['videoUrl'] = 'https://dwkkm.oss-cn-beijing.aliyuncs.com/video/videoUrl20210728.mp4';
        $data['leftQrcode'] = $base64_image;
        $data['rightQrcode'] = $rightQrcode;
        $data['standbyTime'] = 15;//进入屏保时间 单位：s
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    
    /*
     * 我的待约项目
     * 作者 xfwed
     * 日期 2021-01-08
     *
     * @param number ctmId 用户id
     */

    public function myNotYuyueItem() {
        $rule = [
            'ctmId' => 'require',
            'robot_no' => 'require',
            'perPage' => 'integer|egt:1',
            'page' => 'integer|egt:0',
        ];
        $msg = [
            'ctmId.require' => '用户id必须',
            'robot_no.require' => '机器编码必须',
            'perPage.integer' => '每页数量为数字',
            'perPage.egt' => '每页数量最小为1',
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为0',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $ctmId = $all['ctmId'];  
        $robot_no = $all['robot_no']; 
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->value('store_id');
        $perPage = isset($all['perPage']) ? $all['perPage'] : 20;
        $page = isset($all['page']) ? $all['page'] : 0;
        if ($page == 0) {
            $page = 1;
        }

        $offset = ($page - 1) * $perPage;
        
        $list = Yuyue::alias('y')
                ->join('staff s','s.id = y.staff_id','left')
                ->join('item i','i.id = y.item_id','left')
                ->where('y.status','in','1,5,9,10,12')
                ->where('y.ctm_id',$ctmId)
                ->where('y.store_id',$storeId)
                ->field('y.id,y.start_time,y.room_id,y.bed_id,y.status,i.id item_id,i.item_name,i.item_img,i.service_time,s.staff_name')
                ->order('y.start_time asc')
//                ->limit($offset, $perPage)
                ->select();
        
        $data['list'] = $list;
        //查询今天第几位顾客
        $start_time=strtotime(date("Y-m-d",time()));
        $end_time=$start_time+60*60*24;
        $start_time=date("Y-m-d H:i:s",$start_time);       
        $end_time=date("Y-m-d H:i:s",$end_time);    
        $todayCtmlist = Yuyue::alias('y')
                ->join('custom c','c.id = y.ctm_id','left')
                ->where('y.staff_time','between',[$start_time,$end_time])
                ->where('y.store_id',$storeId)
                ->group('ctm_id')
                //->limit('0,5')
                ->column('custom_photo');
        $data['todayCtmNum'] = count($todayCtmlist)+1;
        $data['todayCtmPhoto'] = $todayCtmlist;
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    
    /*
     * 页面二维码
     * 作者 xfwed
     * 日期 2021-01-09
     */

    public function pageQrcode() {
        $rule = [
            'ctmId' => 'require',
            'robot_no' => 'require',
            'type' => 'require',
        ];
        $msg = [
            'ctmId.require' => '用户id必须',
            'robot_no.require' => '机器编码必须',
            'type.require' => '类型必须',
        ];

        $all = input('param.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return $this->ajaxReturn(1, $error, null);
        }
 
        $ctmId = $all['ctmId'];  
        $robot_no = $all['robot_no']; 
        $type = $all['type'];//0我的 1门店 2项目 3美容师 499特权
        $storeId = Db::table('da_machine_store_relation')
                ->where('machine_type',2)
                ->where('robot_no',$robot_no)
                ->value('store_id');
       if($type == 0){
           $note = '※请扫码登录小程序进行操作';
          //n=设备码  m_id=美容师id  i=用户id   si=店铺id   st=登录来源
           $scene = 'si='.$storeId;
           $page = 'pages/index/index';
           $file = new File();
           $qrcode = $file->generateXcxPagecode($scene,$page);
       }elseif ($type == 1) {
           $note = '※请扫码登录小程序进行操作';
           $scene = 'sId='.$storeId;
           $page = 'pages/shopDetail/index';
           $file = new File();
           $qrcode = $file->generateXcxPagecode($scene,$page);
       }elseif ($type == 2) {
           $note = '※请扫码登录小程序进行操作';
           //n=设备码  m_id=美容师id  i=用户id   si=店铺id   st=登录来源  t=1定位到项目列表
           $scene = 'si='.$storeId.'&t=1';
           $page = 'pages/index/index';
           $file = new File();
           $qrcode = $file->generateXcxPagecode($scene,$page);
       }elseif ($type == 3) {
           $note = '※请扫码登录小程序进行操作';
           //cn=城市名  t=1本店 2本市 sid=店铺Id
           $cn = Store::alias('s')
                   ->join('prov_city_area p','p.id = s.city','left')
                   ->where('s.id',$storeId)
                   ->value('p.name');
           $cn=base64_encode($cn);
           $scene = 'cn='.$cn.'&t=2';
           $page = 'pages/index/staffList/staffList';
           $file = new File();
           $qrcode = $file->generateXcxPagecode($scene,$page);
       }elseif ($type == 4) {
           $note = '※请扫码登录小程序进行操作';
           $scene = 's='.$storeId.'&m_id=0&i='.$ctmId;
           $page = 'packageA/pages/nines/nines';
           $file = new File();
           $qrcode = $file->generateXcxPagecode($scene,$page);
       }
       $data['note'] = $note;
       $data['qrcode'] = $qrcode;
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    
    /*
     * 版本更新
     * 作者 xfwed
     * 日期 2021-01-12
     *
     */

    public function version() {
        $rule = [
            'version' => 'require',
        ];
        $msg = [
            'version.require' => '当前版本必须',
        ];

        $all = input('post.');
        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }
        $version = $all['version'];
        $versionArray = explode('.', $version);

        $data = [];
        $row = Db::table('da_machine_version_record')
                ->where('type',6)
                ->field('version_num,apk_url')
                ->find();
        $newVersionArray = explode('.', $row['version_num']);
        if (($newVersionArray[0] > $versionArray[0]) || ($newVersionArray[0] == $versionArray[0] && $newVersionArray[1] > $versionArray[1]) || ($newVersionArray[0] == $versionArray[0] && $newVersionArray[1] == $versionArray[1] && $newVersionArray[2] > $versionArray[2])) {
            $data = [
                'newVersion' => 1,//0没有新版本 1有新版本
                'version' => $row['version_num'],
                'apk_url' => $row['apk_url'],
            ];
        } else {
            $data = [
                'newVersion' => 0,
                'version' => $row['version_num'],
                'apk_url' => $row['apk_url'],
            ];
        }
        return $this->ajaxReturn(0, '查询成功',$data);
    }
    

}

?>